Remove Linked Products Automatically When Deleting a Main Product in WooCommerce
By default, WooCommerce retains synchronized products when a main product is deleted. However, you may want to change this behavior to automatically remove synchronized child products when the main product is deleted. This can be achieved by adding custom code to your site.
Here’s how you can implement this functionality:
add_action( 'before_delete_post', 'wogc_before_delete_post', 1, 2 ); /** * Remove synchronized child products when a main product is deleted. * * @param int $postid The ID of the product being deleted. * @param WP_Post $post The WordPress post object for the product. */ function wogc_before_delete_post( $postid, $post ) { // Check if the product is a main product if ( ! $this->PS->is_main_product( $postid ) ) { return; } global $blog_id; $main_product = new WooGC_PS_main_product( $postid ); foreach ( $main_product->get_children() as $child_shop_id ) { $child_product_id = $this->PS->get_product_synchronized_at_shop( $postid, $blog_id, $child_shop_id ); if ( $child_product_id > 0 ) { switch_to_blog( $child_shop_id ); wp_delete_post( $child_product_id, false ); // Set to true to force deletion restore_current_blog(); } } }
Key Notes:
- Hook: The
before_delete_post
action ensures the function runs before the main product is deleted. - Child Products: Linked child products are identified and removed using the
get_children()
method. - Multisite Handling: The code manages multisite setups by switching blogs during the deletion process.
Add this snippet to your theme’s functions.php
file or a custom plugin to streamline product synchronization cleanup.